<template>
  <div
    class="scrollbar-box"
    ref="line"
    @click="onScrollbarTap"
  >
    <div
      :style="wrapperStyle"
      class="scrollbar-button"
      ref="button"
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
      @mousedown="onButtonDown"
      @touchstart="onButtonDown"
      @focus="handleMouseEnter"
      @blur="handleMouseLeave"
      @keydown.left="onLeftKeyDown"
      @keydown.right="onRightKeyDown"
      @keydown.down.prevent="onLeftKeyDown"
      @keydown.up.prevent="onRightKeyDown"
    >
<!--      <img class="scrollbar-image" src="https://websitedn.yiautos.com/ymc_icon/slidebar.png" />-->
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import EventBus from '../utils/event-bus';

export default {
  name: 'ComScrollBar',
  props: {
    value: Number,
    width: String,
    height: String,
    lineBackground: {
      type: String,
      default: 'lightgray',
    },
    lineWidth: {
      type: Number,
    },
    lineHeight: {
      type: Number,
    },
    ballBackground: {
      type: String,
      default: 'yellow',
    },
    ballSize: {
      type: Number,
      default: 40,
    },
  },
  computed: {
    wrapperStyle() {
      return { left: this.currentPosition + 'px' };
    }
  },
  data() {
    return {
      isClick: false,
      disabled: false,
      dragging: false,
      currentPosition: 0,
      startX: 0,
      biasX: 0, // X偏移
      maxX: 0, // 滑轨最大长度
      lineX: 0 // 滑块最左侧的相对x坐标, 用于计算相对距离
    };
  },
  methods: {
    onScrollbarTap(event) {
      if (this.dragging) {
        return;
      }
      console.log('检测到滚动条点击事件 ==>', event, event.clientX);
      let left = event.clientX - this.lineX - 60;
      if (left < 0) {
        left = 0;
      } else if (left > this.maxX) {
        left = this.maxX;
      }
      this.setPosition(left);
    },
    // 开始拖动
    onButtonDown(event) {
      event.preventDefault();
      this.onDragStart(event);
      window.addEventListener('mousemove', this.onDragging);
      window.addEventListener('touchmove', this.onDragging);
      window.addEventListener('mouseup', this.onDragEnd);
      window.addEventListener('touchend', this.onDragEnd);
      window.addEventListener('contextmenu', this.onDragEnd);
    },
    onDragging: _.throttle(function(event) {
      if (this.dragging) {
        this.isClick = false;
        if (event.type === 'touchmove') {
          event.clientY = event.touches[0].clientY;
          event.clientX = event.touches[0].clientX;
        }
        let left = event.clientX - this.lineX - this.biasX;
        if (left < 0) {
          left = 0;
        } else if (left > this.maxX) {
          left = this.maxX;
        }
        this.setPosition(left);
      }
    }, 20),
    onDragStart(event) {
      this.dragging = true;
      this.isClick = true;
      if (event.type === 'touchstart') {
        event.clientY = event.touches[0].clientY;
        event.clientX = event.touches[0].clientX;
      }
      // 设置开始拖动点
      this.startX = event.clientX;
      const scrollLineRef = this.$refs['line'];
      const scrollButtonRef = this.$refs['button'];
      const scrollLineBounding = scrollLineRef.getBoundingClientRect();
      const scrollButtonBounding = scrollButtonRef.getBoundingClientRect();
      this.lineX = scrollLineBounding.x;
      this.startButtonX = scrollButtonBounding.x;
      this.maxX = scrollLineBounding.width - 120;
      this.biasX = this.startX - this.startButtonX;
    },
    onDragEnd() {
      if (this.dragging) {
        /*
         * 防止在 mouseup 后立即触发 click，导致滑块有几率产生一小段位移
         * 不使用 preventDefault 是因为 mouseup 和 click 没有注册在同一个 DOM 上
         */
        setTimeout(() => {
          this.dragging = false;
          if (!this.isClick) {
            // this.setPosition(0);
          }
        }, 0);
        window.removeEventListener('mousemove', this.onDragging);
        window.removeEventListener('touchmove', this.onDragging);
        window.removeEventListener('mouseup', this.onDragEnd);
        window.removeEventListener('touchend', this.onDragEnd);
        window.removeEventListener('contextmenu', this.onDragEnd);
      }
    },
    onLeftKeyDown() {
      if (this.disabled) return;
      // this.newPosition = parseFloat(this.currentPosition) - this.step / (this.max - this.min) * 100;
      // this.setPosition(0);
    },
    onRightKeyDown() {
      if (this.disabled) return;
      // this.newPosition = parseFloat(this.currentPosition) + this.step / (this.max - this.min) * 100;
      // this.setPosition(0);
    },
    handleMouseEnter() {
    },

    handleMouseLeave() {
    },
    setPosition(position) {
      this.currentPosition = position;
      const percent = position / this.maxX;
      this.$emit('change', percent);
    },
    onHorizontalScrollEvent(position) {
      if (this.dragging) {
        return;
      }
      console.log('滚动条接收到表格滚动 ==>', position, this.maxX);
      this.currentPosition = this.maxX * position;
    }
  },
  mounted() {
    EventBus.$on('TABLE_HORIZONTAL_SCROLL', this.onHorizontalScrollEvent);
    const scrollLineRef = this.$refs['line'];
    const scrollLineBounding = scrollLineRef.getBoundingClientRect();
    this.maxX = scrollLineBounding.width - 120;
  },
  destroyed() {
    EventBus.$off('TABLE_HORIZONTAL_SCROLL');
  }
};
</script>

<style scoped lang="less">
@import '../style/config';

.scrollbar-box {
  width: 100%;
  height: 8px;
  background-color: #eeeeee;
  box-sizing: border-box;
  position: relative;

  .scrollbar-button {
    position: absolute;
    top: 0;
    left: 0;
    width: 120px;
    height: 8px;
    box-sizing: border-box;
    padding: 0;
    margin: 0;
    .clickable;
    background-image: url("https://websitedn.yiautos.com/ymc_icon/slidebar.png");
    background-size: 120px 8px;

    .scrollbar-image {
      width: 120px;
      height: 8px;
      padding: 0;
      margin: 0;
    }
  }
}
</style>

<style lang="less">
.hide-scrollbar {
  .el-table__body-wrapper::-webkit-scrollbar {
    display: none !important;
    height: 0 !important;
  }
}
</style>
